//
//  CTPublishLogic.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/6/13.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTPublishLogic.h"
#import "CTPublishItems.h"
#import "CTDebugManager.h"
#import "CTFile.h"
#import "CTRequestUtil.h"
#import "CTRequestErrorCode.h"
#import "CTUrl.h"
#import "CTHeader.h"
#import "CTTextManager.h"
#import "CTDiscoveryItems.h"


@interface CTPublishLogic ()
{
    NSMutableArray * topicGroupMutableArray;
    NSMutableArray * topicGroupDetailsMutableArray;
    
    NSMutableArray * currentGroupArr;
}

@end


@implementation CTPublishLogic


- (void)dealloc
{
    topicGroupMutableArray = nil;
    topicGroupDetailsMutableArray = nil;
    
    [CTDebugManager showDebugLogInfo:@"dealloc : CTPublishLogic Is Removed!!!"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        topicGroupMutableArray = [NSMutableArray arrayWithCapacity:0];
        topicGroupDetailsMutableArray = [NSMutableArray arrayWithCapacity:0];
        currentGroupArr = [NSMutableArray arrayWithCapacity:0];
    }
    return self;
}

#pragma mark - request -

-(void)emojiListRequest:(CTRequestEditeEmojiListItem *)item
successCompletionHandler:(requestSuccessBlock)successBlock
          failedHandler:(requestFailedBlock)failedBlock
{
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:0];
    @try {
        [param setObject:item.token forKey:@"token"];
        [param setObject:item.lang forKey:@"lang"];
        [param setObject:item.count forKey:@"count"];
        [param setObject:item.page forKey:@"page"];
        [param setObject:item.visitor forKey:@"visitor"];
        
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"组装EditeEmojiList数据错误！"];
    }
    
    [CTRequestUtil sendAsyGetRequest:CT_URL_PUBLISH_EMOJI_LIST(version) withParam:param withCompletionSuccessHandler:^(NSData *data) {
        BOOL isParserSuccess = [self parserEmojiListData:data];
        if (isParserSuccess == YES) {
            successBlock();
        }
        else
        {
            failedBlock();
        }
        
    } withFailedHandler:^(NSError *error) {
        failedBlock();
    }];
}

-(void)bubbleListRequest:(CTRequestEditeBubbleListItem *)item
successCompletionHandler:(requestSuccessBlock)successBlock
           failedHandler:(requestFailedBlock)failedBlock
{
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:0];
    @try {
        [param setObject:item.token forKey:@"token"];
        [param setObject:item.lang forKey:@"lang"];
        [param setObject:item.visitor forKey:@"visitor"];
        
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"组装EditeBubbleList数据错误！"];
    }
    
    [CTRequestUtil sendAsyGetRequest:CT_URL_PUBLISH_BUBBLE(version) withParam:param withCompletionSuccessHandler:^(NSData *data) {
        BOOL isParserSuccess = [self parserBubbleListData:data];
        if (isParserSuccess == YES) {
            successBlock();
        }
        else
        {
            failedBlock();
        }
        
    } withFailedHandler:^(NSError *error) {
        failedBlock();
    }];
}

-(void)publishRequest:(CTRequestPublishUploadItem *)item
successCompletionHandler:(requestSuccessBlock)successBlock
        failedHandler:(requestFailedBlock)failedBlock
{
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:0];
    @try {

        [param setObject:item.lang forKey:@"lang"];
        [param setObject:item.token forKey:@"token"];
        if ([[CTTextManager shareInstance] isBlankString:item.text] == NO)[param setObject:item.text forKey:@"text"];
        if ([[CTTextManager shareInstance] isBlankString:item.group] == NO)[param setObject:item.group forKey:@"groups"];
        [param setObject:item.pic forKey:@"pic"];
        
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"组装发布数据错误！"];
    }
    
    
    NSString * url = CT_URL_PUBLISH_UPLOAD(version);
    NSError * error;
   
    if(param == nil || param.count == 0){
        [CTDebugManager showErrorLogInfo:@"请求发布参数为空,无法请求!"];
        failedBlock(error);
        return;
    }
    
    //配置url
    NSURL *myURL = [NSURL URLWithString:url];
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:CT_HEADER_REQUEST_TIMEOUT_INTERVAL];
    
    //设置type
    [urlRequest setHTTPMethod:@"POST"];
    
    //设置header
    [urlRequest setValue:item.token forHTTPHeaderField:@"token"];
    
   
    
    //设置body
    NSMutableData *data = [self parserPostDataForHttpBody:param];

    [urlRequest setTimeoutInterval: 10];
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
 //   NSString *content2=[[NSString alloc]initWithFormat:@"application/json ; charset=utf-8"];
    //设置HTTPHeader
    [urlRequest setValue:content forHTTPHeaderField:@"Content-Type"];

    [urlRequest setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [urlRequest setHTTPBody:data];
    //http method
    [urlRequest setHTTPMethod:@"POST"];
    

    
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               
                               
                               
                               if( [response isKindOfClass:[NSHTTPURLResponse class]] ){
                                   NSHTTPURLResponse *responseCopy = (NSHTTPURLResponse *)response;
                                   NSInteger statusCode = responseCopy.statusCode;
                                   if(statusCode == 200){
                                       
                                       if (data&&[data length] == 0) {
                                           [CTDebugManager showDebugLogInfo:@"数据为空!!"];
                                           failedBlock();                                           
                                         
                                       }
                                       else
                                       {
                                           [CTDebugManager showDebugLogInfo:@"发布成功!!"];
                                           
                                           BOOL isParserSuccess = [self parserPublishData:data];
                                           
                                           if (isParserSuccess == YES) {
                                               successBlock();
                                           }
                                           else{
                                               failedBlock();
                                           }
                                           
                                       }
                                   }else{
                                       
                                      
                                       
                                       [CTDebugManager showErrorLogInfo:@"发布失败!!"];
                                       
                                       failedBlock();
                                       
                                   }
                               }
                               
                           }];
}






#pragma mark - parser -

-(BOOL)parserEmojiListData:(NSData *)resultData
{
    
    BOOL isParserSuccess = NO;
    
    @try {
        
        NSError * error;
        
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:resultData
                         options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                
                NSString * errCode = [NSString stringWithFormat:@"%@",(NSString *)[deserializedDictionary objectForKey:@"error_code"]];
                if ([errCode isEqualToString:@"0"]) {
                    
                    isParserSuccess = YES;
                    
                    NSDictionary * infoDic = [deserializedDictionary objectForKey:@"info"];
                    
                    //存入文件
                    
                    [CTFile cacheDicFile:[infoDic mutableCopy] fileName:@"emojiList.plist" saveDoc:CTFileDocLibrary savePath:@"cacheData/publish"];
                    
                }
                else{
                    NSString * errDescription = [CTRequestErrorCode errDescription:errCode];
                    [CTDebugManager showErrorLogInfo:errDescription];
                }
            }
        }
        else
        {
            [CTDebugManager showErrorLogInfo:@"解析EmojiList数据错误！"];
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析EmojiList数据错误！"];
    }
    
    return isParserSuccess;
}

-(BOOL)parserBubbleListData:(NSData *)resultData
{
    
    BOOL isParserSuccess = NO;
    
    @try {
        
        NSError * error;
        
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:resultData
                         options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                
                NSString * errCode = [NSString stringWithFormat:@"%@",(NSString *)[deserializedDictionary objectForKey:@"error_code"]];
                if ([errCode isEqualToString:@"0"]) {
                    
                    isParserSuccess = YES;
                    
                    NSDictionary * infoDic = [deserializedDictionary objectForKey:@"info"];
                    
                    //存入文件
                    
                    [CTFile cacheDicFile:[infoDic mutableCopy] fileName:@"bubbleList.plist" saveDoc:CTFileDocLibrary savePath:@"cacheData/publish"];
                    
                }
                else{
                    NSString * errDescription = [CTRequestErrorCode errDescription:errCode];
                    [CTDebugManager showErrorLogInfo:errDescription];
                }
            }
        }
        else
        {
            [CTDebugManager showErrorLogInfo:@"解析BubbleList数据错误！"];
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析BubbleList数据错误！"];
    }
    
    return isParserSuccess;
}


-(BOOL)parserPublishData:(NSData *)resultData
{
    
    BOOL isParserSuccess = NO;
    
    @try {
        
        NSError * error;
        
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:resultData
                         options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
            
                NSString * errCode = [NSString stringWithFormat:@"%@",(NSString *)[deserializedDictionary objectForKey:@"error_code"]];
                if ([errCode isEqualToString:@"0"]) {
                    
                    isParserSuccess = YES;
                    
                }
                else{
                    NSString * errDescription = [CTRequestErrorCode errDescription:errCode];
                    [CTDebugManager showErrorLogInfo:errDescription];
                }
            }
        }
        else
        {
            [CTDebugManager showErrorLogInfo:@"解析发布数据错误！"];
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析发布数据错误！"];
    }
    
    return isParserSuccess;
}
















































- (NSMutableData *)parserPostDataForHttpBody:(NSMutableDictionary *)dic
{
    NSMutableData *myRequestData=[NSMutableData data];
    
    NSMutableData * body = [NSMutableData data];
    
    if (dic.count == 0 || dic == nil){
        [CTDebugManager showErrorLogInfo:@"post数据参数为空!!"];
        return body;}
    
    @try {
        //分界线的标识符
        NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
        //分界线 --AaB03x
        NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
        //结束符 AaB03x--
        NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
        //要上传的图片
        UIImage *image=(UIImage *)[dic objectForKey:@"pic"];
        //得到图片的data
//        NSData* data = UIImagePNGRepresentation(image);
        NSData *data = UIImageJPEGRepresentation(image, 1.0f);
        
//        NSString *_encodedImageStr = [data base64Encoding];

        //http body的字符串
        NSMutableString *body=[[NSMutableString alloc]init];
        //参数的集合的所有key的集合
        NSArray *keys= [dic allKeys];
        
        //遍历keys
        for(int i=0;i<[keys count];i++)
        {
            //得到当前key
            NSString *key=[keys objectAtIndex:i];
            //如果key不是pic，说明value是字符类型，比如name：Boris
            if(![key isEqualToString:@"pic"])
            {
                //添加分界线，换行
                [body appendFormat:@"%@\r\n",MPboundary];
                //添加字段名称，换2行
                [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
                //添加字段的值
                [body appendFormat:@"%@\r\n",[dic objectForKey:key]];
            }
        }
        
        ////添加分界线，换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //声明pic字段，文件名为boris.png
        [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
        //声明上传文件的格式
        [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
       
        //声明结束符：--AaB03x--
        NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
        
        //将body字符串转化为UTF8格式的二进制
        [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [myRequestData appendData:data];
        //加入结束符--AaB03x--
        [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
        
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"组装发布Body数据失败!!"];
    }

    
    return myRequestData;
    
}










//话题逻辑运算json数据生成器
-(NSString *)jsonStrForTopic
{
    NSString * jsonStr = @"";
    
   
    @try {
        
        [currentGroupArr removeAllObjects];
        
        NSMutableDictionary * jsonDic = [NSMutableDictionary dictionaryWithCapacity:0];
        
        if (topicGroupMutableArray.count != 0 && topicGroupDetailsMutableArray.count != 0) {
            
            for (CTEditeEmojiListItem * groupItem in topicGroupMutableArray) {
                NSArray * listArray = groupItem.list;
                NSMutableArray * tempArray = [NSMutableArray arrayWithCapacity:0];
                
                for (CTEditeEmojiListDetailsItem * groupDetailItem in topicGroupDetailsMutableArray) {
                    if ([listArray containsObject:groupDetailItem]) {
                        [tempArray addObject:[NSNumber numberWithInt:[groupDetailItem.scheme_id intValue]]];
                    }
                }
                if (tempArray.count != 0){
                    [jsonDic setObject:[tempArray copy]forKey:groupItem.group_id];
                    CTTopic * topicItem = [[CTTopic alloc] init];
                    topicItem.group_id = groupItem.group_id;
                    topicItem.topic = groupItem.topic;
                    [currentGroupArr addObject:topicItem];
                }
                
                tempArray = nil;
            }
            
        }
       
        if (jsonDic.count != 0)jsonStr = [self dictionaryToJson:[jsonDic copy]];
        
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
      
        jsonDic = nil;
    }
    @catch (NSException *exception) {
        
    }
    
    return jsonStr;
}
-(NSMutableArray *)topicGroupList
{
    return currentGroupArr;
}

-(void)setTopicGroupItem:(CTEditeEmojiListItem *)item
{
    if ([topicGroupMutableArray containsObject:item] == NO) {
        [topicGroupMutableArray addObject:item];
    }
}
-(void)setTopicGroupDetailItem:(CTEditeEmojiListDetailsItem *)item
{

    NSInteger count = item.currentCount;
    count ++;
    item.currentCount = count;
    
   [topicGroupDetailsMutableArray addObject:item];
   
}
-(void)delTopicGroupDetailItem:(CTEditeEmojiListDetailsItem *)item
{
    if ([topicGroupDetailsMutableArray containsObject:item] == YES) {
        
        NSInteger count = item.currentCount;
        if (count > 1) {
            count --;
            item.currentCount = count;
            return;
        }else{
            item.currentCount = 0;
            [topicGroupDetailsMutableArray removeObject:item];
        }
        
        
    }
}

-(NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   
}






@end
